package com.java.gulimall.coupon.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.java.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;

import com.java.gulimall.coupon.dao.SeckillSessionDao;
import com.java.gulimall.coupon.entity.SeckillSessionEntity;
import com.java.gulimall.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
    @Autowired
    private SeckillSkuRelationService relationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatest3DaysSession() {
        // 计算最近3天
        LocalDateTime localDateTime = LocalDateTime.now();
        // "2020-01-23T00:00"
        LocalDateTime start = LocalDateTimeUtil.beginOfDay(localDateTime);
        // "2020-01-26T23:59:59.999999999"
        LocalDateTime offset = LocalDateTimeUtil.offset(localDateTime, 3, ChronoUnit.DAYS);
        LocalDateTime end = LocalDateTimeUtil.endOfDay(offset);
        List<SeckillSessionEntity> list = this.list(new LambdaQueryWrapper<SeckillSessionEntity>().between(SeckillSessionEntity::getStartTime, start, end));
        if (!CollectionUtils.isEmpty(list)) {
            for (SeckillSessionEntity seckillSessionEntity : list) {
                Long id = seckillSessionEntity.getId();
                List<SeckillSkuRelationEntity> entities = relationService.list(new LambdaQueryWrapper<SeckillSkuRelationEntity>().eq(SeckillSkuRelationEntity::getPromotionSessionId, id));
                seckillSessionEntity.setRelationSkus(entities);
            }
        }
        return list;
    }

}